import { MenuProps } from "antd";
import { mainRoutes } from "@/router/main-routes";

// 从 token 解析 role（假设 token 为 JWT）
function getCurrentUserRole() {
  const token = localStorage.getItem('token');
  if (!token) return '';
  try {
    const payload = JSON.parse(atob(token.split('.')[1]));
    return payload.role || '';
  } catch {
    return '';
  }
}

type MenuItem = Required<MenuProps>["items"][number];

function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[]
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
  } as MenuItem;
}

// 递归构建菜单，增加权限过滤
function buildMenu(routes: any[], userRole: string): MenuItem[] {
  return routes
    .filter((route) => route.meta?.isShowNav && (!route.meta?.roles || route.meta.roles.includes(userRole)))
    .map((route) =>
      getItem(
        route.meta.title,
        route.path,
        route.meta.icon,
        route.children ? buildMenu(route.children, userRole) : undefined
      )
    );
}

const userRole = getCurrentUserRole();
const items: MenuItem[] = buildMenu(mainRoutes[0].children, userRole);

export default items;
